<template>
  <a-drawer
    v-model:visible="vdata.visible"
    :maskClosable="false"
    :body-style="{ paddingBottom: '80px' }"
    width="40%"
    class="drawer-width"
    @close="onClose"
  >
    <template #title>
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <span v-if="vdata.isAdd">新建微信代金券</span>
        <span v-else>{{ vdata.disabled ? "追加" : "修改" }}微信代金券</span>
        <!-- 只有新增和草稿状态下 有保存草稿的功能 -->
        <a-button
          :disabled="vdata.disabled"
          @click="onSaveDraft"
        >
          保存草稿
        </a-button>
      </div>
    </template>
    <Step :current-step="vdata.currentStep" :steps="stepsConfig" />


    <a-form
      v-if="vdata.currentStep == 0"
      ref="stepForm0Ref"
      :model="vdata.baseObject"
      layout="vertical"
      :wrapperCol="{ span: 24 }"
      labelAlign="left"
      :hideRequiredMark="false"
      :rules="vdata.step0Rules"
      :scrollToFirstError="true"
      style="margin-top: 20px"
    >
      <a-row type="flex" justify="space-between" wrap="true">
        <a-col :span="11">
          <a-form-item label="机构" name="agentNo">
            <GzTreeSelect
              v-if="vdata.visible"
              ref="gzThreeRef"
              v-model:value="vdata.baseObject['agentNo']"
              :disabled="vdata.disabled"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="卡券名称" name="couponName">
            <a-input
              v-model:value="vdata.baseObject['couponName']"
              :disabled="vdata.disabled"
              placeholder="请输入卡券名称"
              :maxlength="16"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="卡券名称副标题" name="couponDes">
            <a-input
              v-model:value="vdata.baseObject['couponDes']"
              :disabled="vdata.disabled"
              placeholder="请输入卡券名称副标题"
              :maxlength="16"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="可用时间" name="couponTime">
            <a-range-picker
              v-model:value="vdata.baseObject['couponTime']"
              :disabled="vdata.disabled"
              value-format="YYYY-MM-DD"
              :disabledDate="
                (current) =>
                  current && current < dayjs().endOf('day').subtract(1, 'day')
              "
              :allowClear="false"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item
            label="有效期内，用户领券后多少天内可用"
            name="availableDays"
          >
            <a-input
              v-model:value="vdata.baseObject['availableDays']"
              :disabled="vdata.disabled"
              placeholder="有效天数"
              style="width: 100%"
              oninput="value=value.replace(/[^\d]/g,'')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="卡券张数" name="couponNum">
            <a-input-number
              v-model:value="vdata.baseObject['couponNum']"
              :precision="0"
              placeholder="请输入卡券张数"
              :min="vdata.minCouponNum"
              style="width: 100%"
              :disabled="vdata.isDetail"
            />
            <span
              v-if="vdata.disabled"
              class="gz-tip-text"
            >数量只能增加，不能减少</span>
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="卡券面额（元）" name="couponPrice">
            <a-input-number
              v-model:value="vdata.baseObject['couponPrice']"
              :disabled="vdata.disabled"
              placeholder="请输入卡券面额"
              :precision="2"
              min="0.01"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="活动预算（元）">
            <a-input
              v-model:value="vdata.baseObject['couponAmount']"
              placeholder="0"
              min="0.01"
              :precision="2"
              disabled
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item name="thirdParam">
            <template #label>
              三方回参 
            </template>
            <a-input
              v-model:value="vdata.baseObject['thirdParam']"
              :disabled="vdata.disabled"
              placeholder="请输入三方回参"
            />
          </a-form-item>
        </a-col>
    
        <a-col :span="11">
          <a-form-item name="payAuthId">
            <template #label>
              出资方 
            </template>
            <a-select
              ref="select"
              v-model:value="vdata.baseObject['payAuthId']"
              placeholder="请选择出资方"
              :disabled="vdata.disabled"
            >
              <a-select-option v-for="(item,index) in butorList" :key="index" :value="item.payAuthId">
                {{ item.ifName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col :span="11">
          <a-form-item label="起付金额(满多少元使用)" name="payAmount">
            <a-input-number
              v-model:value="vdata.baseObject['payAmount']"
              :disabled="vdata.disabled"
              placeholder="请输入起付金额"
              :precision="2"
              style="width: 100%"
              :min="0.01"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="卡券规则" name="remark">
            <a-textarea
              v-model:value="vdata.baseObject['remark']"
              :disabled="vdata.disabled"
              placeholder="请输入卡券规则"
              :rows="4"
            />
            <span class="gz-tip-text">换行符：\n</span>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否限卡支付" name="isRestrictBank">
            <a-radio-group v-model:value="vdata.baseObject['isRestrictBank']" :disabled="vdata.disabled" @change="changeGroupRadio(vdata.baseObject['isRestrictBank'])">
              <a-radio :value="0">不限制卡支付</a-radio>
              <a-radio :value="1">限制邮储借记卡支付（邮储卡）</a-radio>
              <a-radio :value="2">限制邮政贷记卡（信用卡）</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <Setting
      v-if="vdata.currentStep==1"
      ref="stepForm1Ref"
      :awardSettingId="awardSettingId"
      :disabled="vdata.disabled"
      :isDisabled="vdata.isDisabled || vdata.disabled"
      :isDetail="vdata.isDetail"
      @sendData="handleChildrenData"
    />
    <MerchantFrom
      v-if="vdata.currentStep == 2"
      ref="stepForm2Ref"
      :awardId="vdata.baseObject.couponId"
      :awardType="awardType"
      :isDetail="vdata.isDetail"
      :isDisabled="vdata.isDisabled || vdata.disabled"
    />
    <PersonnelFrom
      v-if="vdata.currentStep == 3"
      ref="stepForm3Ref"
      :awardId="vdata.baseObject.couponId"
      :awardType="awardType"
      :isEmployee="vdata.baseObject.isEmployee"
      :isDisabled="vdata.isDisabled || vdata.disabled"
      :isDetail="vdata.isDetail"
    />
    <InstitutionFrom
      v-if="vdata.currentStep == 4"
      ref="stepForm4Ref"
      :awardId="vdata.baseObject.couponId"
      :awardType="awardType"
      :isAllocation="vdata.baseObject.isAllocation"
      :agentNo="vdata.baseObject.agentNo"
      :isDisabled=" vdata.isDisabled || vdata.disabled"
      :isDetail="vdata.isDetail"
      :isPush="vdata.disabled"
    />
    <div class="drawer-btn-center">
      <a-button
        v-if="vdata.currentStep != 0"
        style="margin-right: 8px"
        @click="onSteps(-1)"
      >
        <step-backward-outlined />
        上一步
      </a-button>
      <a-button
        v-if="vdata.currentStep != 4"
        :loading="vdata.btnLoading"
        style="margin-right: 8px"
        @click="onSteps(1)"
      >
        <step-forward-outlined />
        下一步
      </a-button>
      <a-button
        v-if="vdata.currentStep == 4"
        type="primary"
        :loading="vdata.btnLoading"
        @click="onSave" 
      >
        <check-outlined />
        保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import{$getCouponDetail,$couponAddOrEdit,$addStting,$updateStting,$getContributorList,$couponState}from '@/api/awardMange/coupon/index'
import {reactive,ref,getCurrentInstance,watch,computed,nextTick,onMounted,} from 'vue'
import dayjs from 'dayjs'
import numberUtil from '@/utils/numberUtil.js'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
 import Step from '../components/step/index.vue'
 import PersonnelFrom from '../components/PersonnelFrom/index.vue'
 import MerchantFrom from '../components/MerchantFrom/index.vue'
import InstitutionFrom from '../components/InstitutionFrom/index.vue'
import Setting from '../components/setting/index.vue'
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
NProgress.configure({ showSpinner: false })
const awardType = ref(0)
const stepForm3Ref = ref()
const stepForm2Ref = ref()
const stepForm1Ref = ref()
const stepForm0Ref = ref()
const couponIdOne = ref()
const couponIdUpdate = ref()
// 获取当前实例的代理对象
const { proxy }: any = getCurrentInstance()
// 步骤配置
const stepsConfig = ref([
  { title: '卡券基本信息' },
  { title: '卡券配置信息' },
  { title: '可核销商户' },
  { title: '可派发人员' },
  { title: '卡券数量配置' }
])


// 传递过去选中的元素
const activeKey = ref('1')
const activeKey1 = ref('1') 
const props = defineProps(['callbackFunc', 'record1'])
const vdata: any = reactive({
  btnLoading: false,
  currentStep: 0,
  isAdd: true, // 新增 or 修改页面标志
  baseObject: {}, // 数据对象
  visible: false, // 是否显示弹层/抽屉
  minCouponNum: 1, // 卡券张数限制 卡券在配置中状态时 卡券张数只可增加不能减少
  disabled: false, // 在下架修改时 只允许修改卡券数量 且只能增加不能减少
    step0Rules: {
    isLimitUser:[ { required: true, trigger: 'blur', message: '发放限制不能为空',} ],
    isOpenReceipt:[ { required: true, trigger: 'blur', message: '回执不能为空',} ],
    receiptType: [{ required: true, message: '回执类型不能为空', trigger: 'blur' }], // 回执类型
    couponName: [ { required: true, message: '卡券名称不能为空', trigger: 'blur' }, ],
    couponTime: [ { required: true, message: '卡券开始时间/结束时间不能为空', trigger: 'blur', }, ],
    limitUserContent:[{required: true, message: '请选择发放客户等级限制', trigger: 'blur'}],
    couponNum: [ { required: true, message: '卡券张数不能为空', trigger: 'blur' }, ],
    couponPrice: [ { required: true, message: '卡券面额不能为空', trigger: 'blur' },  ],
    agentNo: [ { required: true, message: '请选择机构', trigger: ['blur', 'change'] }, ],
    remark: [{ required: true, message: '卡券规则不能为空', trigger: 'blur' }],
    isRestrictBank: [{ required: true, message: '限卡支付不能为空', trigger: 'blur' }],
    verifiedScore: [ { required: true, message: '核销后奖励福分不能为空', trigger: 'blur' }, ],
    scoreOverType: [ { required: true, message: '过期规则类型不能为空', trigger: 'blur' }, ],
    payAmount: [ { required: true, trigger: 'blur', validator: payAmountValidator }, ],
  },
})
/** 起付金额校验 */
function payAmountValidator() {
  const { payAmount, couponPrice } = vdata.baseObject
  if (!payAmount) {
    return Promise.reject('起付金额(满多少元可用)不能为空')
  }
  if (couponPrice && payAmount <= couponPrice) {
    return Promise.reject('起付金额(满多少元可用)不能小于卡券面额')
  }
  return Promise.resolve()
}


// 改变单选框
function changeGroupRadio(value){
  if(value ==0){
    vdata.baseObject.remark = '1. 该消费券只可在邮政指定商户处使用。\n2. 消费券在订单结算的时候抵扣相应金额，不能直接兑换现金。\n3. 每个订单仅可使用一张消费券，使用后即失效。\n4. 最终解释权归邮政所有。'
  }else if(value ==1){
    vdata.baseObject.remark = '1. 该消费券只可在邮政指定商户处使用。\n2. 消费券在订单结算的时候抵扣相应金额，不能直接兑换现金。\n3. 每个订单仅可使用一张消费券，使用后即失效。\n4. 限制邮储借记卡支付。\n5. 最终解释权归邮政所有。'
  }else if(value ==2){
    vdata.baseObject.remark = '1. 该消费券只可在邮政指定商户处使用。\n2. 消费券在订单结算的时候抵扣相应金额，不能直接兑换现金。\n3. 每个订单仅可使用一张消费券，使用后即失效。\n4. 限制信用卡支付。\n5. 最终解释权归邮政所有。'
    
  }
}

const  baseObjectSetting = ref()

// 接受子组件传递过来的基本信息限制配置的对象 
 function handleChildrenData(childrenObject:any){
  baseObjectSetting.value = childrenObject.childrenbaseObject

  if(vdata.isAdd){
    vdata.baseObject.couponId = couponIdOne.value
  }else{
    vdata.baseObject.couponId = couponIdUpdate.value
  }
  
 }


// 回执类型切换 根据回执类型 动态渲染回执内容表格
/**
 * 监听卡券张数和面额 自动计算卡券预算
 */
watch(
  [() => vdata.baseObject.couponNum, () => vdata.baseObject.couponPrice],
  (newVal, oldVal) => {
    if (oldVal[0] === undefined && oldVal[1] === undefined) return
    if (vdata.baseObject.couponNum && vdata.baseObject.couponPrice) {
      vdata.baseObject.couponAmount = numberUtil.computeNumber(
        vdata.baseObject.couponNum,
        '*',
        vdata.baseObject.couponPrice
      ).result
    }
  },
  { immediate: false }
)
/**
 * 监听活动时间 自动处理开始结束时间
 */
watch(
  () => vdata.baseObject.couponTime,
  (newVal, oldVal) => {
    if (newVal && newVal.length === 2) {
      vdata.baseObject.startTime = newVal[0]
      vdata.baseObject.endTime =
        dayjs(newVal[1]).format('YYYY-MM-DD') + ' 23:59:59'
    }
  }
)
/**
 * 切换步骤
 */
// let flag = false // 标志 是否切换过第三步 flag
function onSteps(step: number) {
  if (step < 0) {
    
    vdata.currentStep--
  } else {
    if(vdata.isDetail){
      vdata.currentStep++
    }else{
      proxy.$refs['stepForm' + vdata.currentStep + 'Ref']
      .validate()
      .then(() => {   
        // 第一步网络请求 卡券信息
        if (vdata.currentStep === 0) {
            step0Request(false)
        }else if(vdata.currentStep===1){
            saveStting()
        } else if (vdata.currentStep === 2 || vdata.currentStep === 3) {
          
          // 第二步 上传可核销商户清单
          if(vdata.currentStep === 3){
          // 调用员工组件暴漏的 handleIsEmployeeChange
          proxy.$refs['stepForm3Ref'].handleIsEmployeeChange()
          
          }
          vdata.currentStep++
        }
      })
      .catch((e) => {
        console.log(e)
      })
    }

  }
}
/**
 * 第一步网络请求 卡券信息
 */
function step0Request(isDraft: boolean, showMsg = false) {
  var uploadObject = JSON.parse(JSON.stringify(vdata.baseObject))  
  // 清除冗余数据
  delete uploadObject.agents
  const {
    couponId,
    couponPrice,
    couponAmount,
    payAmount,
} = uploadObject
  const METHOD = couponId ? 'PUT' : 'POST'
  uploadObject.couponType = 5
  if (couponPrice) {
    uploadObject.couponPrice = numberUtil.computeNumber(
      couponPrice,
      '*',
      100
    ).result
  }
  if (couponAmount) {
    uploadObject.couponAmount = numberUtil.computeNumber(
      couponAmount,
      '*',
      100
    ).result
  }
  if (payAmount) {
    uploadObject.payAmount = numberUtil.computeNumber(
      payAmount,
      '*',
      100
    ).result
  }
  // 删除冗余数据
  delete uploadObject.awardMchList
  $couponAddOrEdit(METHOD, uploadObject).then((res) => {
    console.log(res,'res111111')
    if (METHOD === 'POST') {
       couponIdOne.value = res.couponId
       vdata.baseObject.couponId = res.couponId
    }
    if (isDraft) {
      if (showMsg) {
        $infoBox.message.success('保存成功')
        onClose()
      }
      return
    }
    vdata.currentStep++
  })
}
// 通过awardSettingId来查配置的详情
const awardSettingId = ref()
function saveStting(){  
   const uploadObject =  proxy.$refs['stepForm1Ref'].changehadleSaveStting()
    uploadObject.awardId =  vdata.baseObject.couponId
     uploadObject.awardType = awardType.value  
  if(awardSettingId.value||uploadObject.awardSettingId){
  uploadObject.awardSettingId =  awardSettingId.value?awardSettingId.value:uploadObject.awardSettingId
  $updateStting(uploadObject).then((res) => { 
       vdata.currentStep++
  })
  }else{
  $addStting(uploadObject).then((res) => {      
      awardSettingId.value = res
    vdata.currentStep++
  })
  }

}


/**
 * 保存草稿
 */
function onSaveDraft() {
  if (vdata.currentStep == 0) {
    // 在第一步 保存草稿
    // 移除校验结果
    clearFieldValidate()
    proxy.$refs['stepForm' + vdata.currentStep + 'Ref']
      .validate(['agentNo', 'couponName', 'payAmount'])
      .then(() => {
        if(!vdata.isDetail){
          step0Request(true, true)
        }
          
      })
  } else if (vdata.currentStep === 1) {
      saveStting()
    // 第二步 保存草稿
    onClose()
  } else if(vdata.currentStep==2) {
    $infoBox.message.success('保存成功')
    onClose()
  }else if(vdata.currentStep==3){
     proxy.$refs['stepForm3Ref'].handleIsEmployeeChange()
      $infoBox.message.success('保存成功')
    onClose()
  }else{
     proxy.$refs['stepForm4Ref'].handleIsAllocationChange()
      $infoBox.message.success('保存成功')
     onClose()

  }
}

/**
 * 弹出层打开事件
 * @param couponId 卡券ID
 */
function show(couponId:any, disabled:any,isDisabled,isDetail,minCouponNum:any) {
  activeKey.value = '1'
  activeKey1.value = '1'
  vdata.isAdd = !couponId
  // 数据清空
  vdata.currentStep = 0
  vdata.btnLoading = false
  awardSettingId.value = null
  clearFieldValidate()
  // 数据重置
  vdata.baseObject = {
    state: 0, // 默认草稿状态
    isRestrictBank: 0,  // 是否限卡支付
    remark: '1. 该消费券只可在邮政指定商户处使用。\n2. 消费券在订单结算的时候抵扣相应金额，不能直接兑换现金。\n3. 每个订单仅可使用一张消费券，使用后即失效。\n4.最终解释权归邮政所有。'
  }
  vdata.minCouponNum = minCouponNum
    // 如果点击是详情，保存不调用接口
    console.log(vdata.isDetail,'vdata.isDetail')
  vdata.isDetail = isDetail
  vdata.isDisabled = isDisabled
  vdata.disabled = disabled
  if (vdata.isAdd) {
    // 新增
    vdata.visible = true // 立马展示弹层信息
  } else {
    $getCouponDetail({ couponId })
      .then((res) => {
        // 深拷贝 coupon 对象以便修改
        vdata.baseObject = {
          ...res,
          couponPrice: numberUtil.computeNumber(res.couponPrice, '/', 100)
            .result,
          couponAmount: numberUtil.computeNumber(res.couponAmount, '/', 100)
            .result,
          payAmount: numberUtil.computeNumber(res.payAmount, '/', 100)
            .result,
          couponTime: [res.startTime, res.endTime],
        isAllocation:res.awardSetting?.isAllocation,
        isEmployee:res.awardSetting?.isAllocationUser
        }        
          couponIdUpdate.value = res.couponId
        if(res.awardSetting){
        //  修改的时候拿到settingid去查setting信息
         awardSettingId.value = res.awardSetting.awardSettingId
        }
      
        vdata.visible = true // 立马展示弹层信息
      })
    }

}

/**
 * 清除表单字段验证
 */
function clearFieldValidate() {
  // 清除当前步骤的验证
  if (proxy.$refs['stepForm' + vdata.currentStep + 'Ref'] != undefined) {    
    proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].clearValidate() // 清除验证
  }
}
/**
 * 关闭弹层
 */
function onClose() {
  if(vdata.isDetail){
    vdata.baseObject.agentNo = '' // 关闭弹层时清空选择机构 以再重新打开时触发机构树请求
  vdata.visible = false
  }else{
    props.callbackFunc()
  vdata.baseObject.agentNo = '' // 关闭弹层时清空选择机构 以再重新打开时触发机构树请求
  vdata.visible = false
  }

}

// 保存
function onSave(){
  if(vdata.isDetail){
    onClose()
  }else{
    proxy.$refs['stepForm4Ref'].handleIsAllocationChange()
    $couponState( {couponId:vdata.baseObject.couponId,state: 2,})
          .then(() => {
            $infoBox.message.success('保存成功')
            onClose()
          })
  }
    
}
/**
 * 暴露接口
 */
defineExpose({
  show,
})


const  butorList = ref([]) as any
function fundingParty(){
  $getContributorList({}).then(res=>{ 
    butorList.value = res
  })
}

onMounted(()=>{
  
fundingParty()
})
</script>
<style lang="less" scoped>
.choseText {
  color: #1890ff;
}
.margin-left {
  margin-left: 10px;
}
.mt10 {
  margin-top: 10px;
}
.mb0 {
  margin-bottom: 0;
}

.a-radio {
  line-height: 40px;
}

.tag {
  position: absolute;
  right: -20px;
  top: 8px;
}
.del-all{
  margin-top: 20px;
  margin-left: 30px;
}
.remark {
  color: #999999;
}
:deep(.ant-space .ant-space-item:nth-of-type(2)) {
  flex-grow: 1;
}
</style>
